package com.authenticateCenter.assembler;

import com.authenticateCenter.domain.entity.Role;
import com.authenticateCenter.domain.vo.RoleVo;
import java.util.List;
import java.util.stream.Collectors;

import com.authenticateCenter.service.IAuthorityService;
import com.authenticateCenter.service.IRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.common.mybaits.CustomPage;
import com.common.mybaits.PageFactory;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import static com.authenticateCenter.factory.AuthorityFactory.AUTHORITY_CONVERT;
import static com.authenticateCenter.factory.RoleFactory.ROLE_CONVERT;


/**
 * @author 大忽悠
 */
@Component
@RequiredArgsConstructor
public class RoleAssembler implements InfoAssembler<RoleVo,Integer,Integer> {
    private final IRoleService iRoleService;
    private final IAuthorityService iAuthorityService;

    @Override
    public RoleVo assembler(Integer uid) {return null;}

    @Override
    public List<RoleVo> assemblers(CustomPage customPage, Integer uid) {
        List<Role> roles = getRoles(customPage,uid);
        if(roles==null || roles.isEmpty()){
            return null;
        }
        List<RoleVo> roleVos = roles.stream().map(role -> ROLE_CONVERT.toRoleVo(role)).collect(Collectors.toList());
        roleVos.forEach(roleVo -> roleVo.setAuthorityList(iAuthorityService.getAuthoritysByRid(roleVo.getId(), null).stream()
                .map(authority -> AUTHORITY_CONVERT.toAuthorityVo(authority)).collect(Collectors.toList())));
        return roleVos;
    }

    private List<Role> getRoles(CustomPage customPage, Integer uid) {
        if(uid==null){
            return getRolesByPage(customPage,null);
        }
        return iRoleService.getRolesByUid(customPage,uid);
    }

    /**
     * @param customPage 分页信息
     * @param queryWrapper 查询条件
     * @return 角色列表
     */
    private List<Role> getRolesByPage(CustomPage customPage, QueryWrapper<Role> queryWrapper) {
        return CustomPage.getResult(customPage,new Role(),iRoleService,queryWrapper);
    }
}
